<template>
  <div class="app-content">
    <h2 class="font-medium mb-5">代码提交</h2>
    <div v-if="updateVersion" class="flex justify-between items-center">
      <div>
        <p><span class="text-gray-500">当前版本：</span>{{ updateVersion.version || '无' }}</p>
        <p class="mt-2.5"><span class="text-gray-500">新版本：</span>{{ updateVersion.new_version }}</p>
      </div>
      <div>
        <p v-if="updateVersion.update">有新版本可以上传</p>
        <p v-else>当前版本已经提交到测试</p>
        <p class="mt-2.5">
          <span class="text-gray-500">更新说明：{{ updateVersion.desc }}</span>
        </p>
      </div>
      <div>
        <el-button type="primary" @click="onGetBindDomainForm()">配置域名</el-button>
        <el-button v-if="updateVersion.update" type="primary" @click="onUploadCode()">提交代码</el-button>
        <el-button v-else @click="onUploadCode()">重新提交</el-button>
      </div>
    </div>
    <div v-else class="flex items-center justify-center h-25 text-gray-500">暂无新版本</div>
    <dk-form ref="form" :form-data="formData" :is-dialog="true" top="5vh" />
  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBindDomainForm, getDouyinNewVersion, uploadDouyinVersion } from '@/api/platform/app/douyin_open'

defineOptions({
  name: 'DkDouyinUploadContainer'
})

const props = defineProps({
  row: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['update'])

const updateVersion = ref(null)
const formData = ref(null)
const form = ref(null)
const defaultApp = inject('defaultApp')

const platformAppId = computed(() => {
  return defaultApp.value.id
})

const onGetBindDomainForm = () => {
  getBindDomainForm(defaultApp.value.id).then((res) => {
    console.log(res)
    formData.value = res.data
    form.value.show()
  })
}

const onUploadDouyinVersion = (desc) => {
  uploadDouyinVersion(defaultApp.value.id, desc).then((res) => {
    ElMessage.success(res.msg)
    emit('update')
  })
}

const onUploadCode = () => {
  ElMessageBox.prompt('请填写提交代码的更新内容', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: updateVersion.value.desc || '新版本'
  })
    .then(({ value }) => {
      onUploadDouyinVersion(value)
    })
    .catch(() => {
      // 用户取消操作
    })
}

const onGetDouyinNewVersion = () => {
  getDouyinNewVersion(platformAppId.value)
    .then((res) => {
      updateVersion.value = res.data
    })
    .catch((res) => {
      console.log('getDouyinNewVersion', res)
    })
}

onMounted(() => {
  onGetDouyinNewVersion()
})
</script>
